package schedule

import (
	"context"
	"fmt"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"github.com/gorhill/cronexpr"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/go-log"
	"time"
)

func taskProc(_ context.Context, h func(task db.BatchSchedule) error) (err error) {

	if h == nil {
		return
	}
	task, e := getTask()
	if e != nil {
		return
	}
	expr, e := cronexpr.Parse(task.Cron)
	if e != nil {
		log.Info(e)
		return
	}
	currentRun := task.NextRun
	nextRun := expr.Next(currentRun)
	e = h(task)

	task.NextRun = nextRun
	updateTask(task, e)
	return
}

func getTask() (task db.BatchSchedule, err error) {
	var list []db.BatchSchedule
	_, err = app.GetOrm().Context.QueryTable(new(db.BatchSchedule)).
		Limit(1).
		Filter("next_run__lt", time.Now()).
		OrderBy("next_run").All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 { // no task
		err = fmt.Errorf("no task")
		return
	}
	task = list[0]
	return
}

func updateTask(task db.BatchSchedule, err error) {
	if err != nil {
		task.LastState = db.ScheduleStateFail
		task.ScheduleMemo.Memo = fmt.Sprintf("%v", err)
	} else {
		task.LastState = db.ScheduleStateOk
		task.ScheduleMemo.Memo = "-:"
	}
	_, err = app.GetOrm().Context.Update(&task, "last_state", "memo", "next_run")
}
